package com.toobigtofail.entities
{
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.b2Body;
	
	import com.toobigtofail.images.ShapeImage;
	import com.toobigtofail.shapes.IShape;
	
	import fabulaexmachina.box2fp.Box2DEntity;
	import fabulaexmachina.box2fp.graphics.SuperGraphiclist;
	
	public class Enemy extends Box2DEntity
	{
		public static const TYPE:String = "enemy";
		
		public var _goForce:b2Vec2;
		private var _shape:IShape;
		private var _initOptions:Object;
		private var _image:ShapeImage;
		
		public function Enemy(shape:IShape, goForce:b2Vec2=null, angle:Number=0, image:ShapeImage=null)
		{	
			_goForce = goForce;
			_shape = shape;
			_initOptions = {angle: angle};
						
			super(shape.X, shape.Y, shape.Width, shape.Height, b2Body.b2_staticBody);
			type = Enemy.TYPE;
			if (image) {
				_image = image;
				_image.type = "Enemy";
				_image.angle = 0;
				_image.offsetForBox2D(Width, Height);
				graphic = new SuperGraphiclist(_image);
			}
		}
				
		override public function added():void {
			super.added();
			
			_shape.buildShape(body);
			this.angle = _initOptions.angle;
		}
		
		override public function update():void {
			super.update();
			
			if (_image) {
				_image.centerOrigin();
			}
		}
		
		public function go():void {
			body.SetType(b2Body.b2_dynamicBody);
			if (_goForce) {
				body.ApplyForce(_goForce, body.GetWorldCenter());
			}
		}
		
		public function serialize():XML {
			var e:XML = <enemy/>;
			if (_goForce) {
				e.@goX = _goForce.x;
				e.@goY = _goForce.y;
			}
			if (_image) {
				var i:XML = <image/>;
				i.@shape = _image.shape;
				e.appendChild(i);
			}
			e.appendChild(_shape.serialize());
			
			return e;
		}
		
		public function get shape():IShape { return _shape; }
		public function get image():ShapeImage { return _image; }
	}
}